package com.zx.cloud.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zx.cloud.ApiVersion;
import com.zx.cloud.Shift;
import com.zx.cloud.common.auth0.jwt.Token;
import com.zx.cloud.common.auth0.jwt.TokenGenerator;
import com.zx.cloud.common.auth0.jwt.exceptions.JWTCreationException;
import com.zx.cloud.common.filter.CurrentUserId;
import com.zx.cloud.common.filter.IgnoreAuth;
import com.zx.cloud.common.filter.MagicConstants;
import com.zx.cloud.common.token.PasswordHashUtil;
import com.zx.cloud.domain.Resource;
import com.zx.cloud.domain.User;
import com.zx.cloud.model.request.ManagerLoginRequest;
import com.zx.cloud.model.response.ObjectDataResponse;
import com.zx.cloud.service.LogService;
import com.zx.cloud.service.ResourceService;
import com.zx.cloud.service.UserService;
import com.zx.cloud.util.CookieManager;


/**
 * 用户表
 */
@RestController
@RequestMapping(value = ApiVersion.PROVIDER_V1_PREFIX+"/user")
public class LoginController{

	private static final Logger logger=Logger.getLogger(LoginController.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private LogService logService;
	
	@IgnoreAuth
	@ApiOperation(value = "管理系统用户登录", notes = "管理系统用户登录")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Token> login(HttpServletRequest request,HttpServletResponse response,@RequestBody ManagerLoginRequest loginRequest) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException{
		User findUser = new User();
		findUser.setUsername(loginRequest.getUsername());
		User user = userService.findOne(findUser);
		if (user == null) {
			 Shift.fatal(StatusCode.USER_NOT_EXISTS,"用户不存在");
		}
		if (!PasswordHashUtil.validatePassword(loginRequest.getPassword(), user.getPassword())) {
			 Shift.fatal(StatusCode.INVALID_CREDENTIAL,"凭证错误");
		}
		List<Resource> resources=resourceService.findPermissionsByUserId(user.getId());
		Map<String, Object> claims=new HashMap<String, Object>();
    	claims.put(MagicConstants.SESSION_USER_ID,user.getId());
    	List<String> aList=new ArrayList<String>();
    	for (Resource resource : resources) {
			if(StringUtils.isEmpty(resource.getUrl())){
				aList.add(resource.getUrl());
			}
		}
    	claims.put(MagicConstants.SESSION_USER_PERMISSIONS,aList);
    	Token token=TokenGenerator.create(claims);
    	user.setBeforeLoginDate(user.getLoginDate());
    	user.setLoginDate(OffsetDateTime.now());
    	userService.updateLoginTime(user);
    	new CookieManager(request, response).setCookie(MagicConstants.AUTH_TOKEN, token.getToken(), 7*24*60*60);
    	logService.addLog(user.getId(), "用户登录", 0);
		return new ObjectDataResponse<Token>(token);
	}
	
	@ApiOperation(value = "登录用户-主页面提示信息", notes = "登录用户-主页面提示信息")
	@RequestMapping(value = "/loginFind", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<User> loginFind(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody User user) {
		User success=userService.loginFind(userId);
		logService.addLog(user.getId(), "主页面提示", 0);
		return new ObjectDataResponse<User>(success);
	}

	@ApiOperation(value = "用户管理-修改密码", notes = "用户管理-修改密码")
	@RequestMapping(value = "/updatePassWord", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> updatePassWord(@CurrentUserId Long userId,@RequestBody User user){
		user.setId(userId);
		int success=userService.updatePSD(user);
		logService.addLog(user.getId(), "修改密码", 0);
		return new ObjectDataResponse<Integer>(success);
	}
	
	/**
	 * @Description:登陆 注册 忘记密码 发送短信验证接口
	 *                fromType 状态码 '0':登陆 '1'：注册 '2'：忘记密码
	 * @author Yan Weiwei
	 * @Create Time: 2017年10月28日上午9:46:40
	 * @param userId
	 * @param userPhone
	 * @param fromType
	 * @return
	 */
	@IgnoreAuth
	@ApiOperation(value = "验证手机-获取验证码", notes = "验证手机-获取验证码")
	@RequestMapping(value = "/sendSMS", method = RequestMethod.GET)
	@ResponseBody
	public ObjectDataResponse<Integer> sendSMS(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestParam String userPhone,@RequestParam String fromType){
		
		int success=userService.handleSmsCode(userId, userPhone, fromType);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@IgnoreAuth
	@ApiOperation(value = "判断验证码对错", notes = "判断验证码对错")
	@RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
	@ResponseBody
	public ObjectDataResponse<Integer> verifyCode(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestParam String userPhone, @RequestParam String userCode){
		
		int success=userService.verifySmsCode(userId, userPhone, userCode);
		return new ObjectDataResponse<Integer>(success);
	}
	
}